import 'package:enjoy_plus_hm/pages/house/components/house_item.dart';
import 'package:enjoy_plus_hm/utils/event_bus.dart';
import 'package:enjoy_plus_hm/utils/http.dart';
import 'package:enjoy_plus_hm/utils/toast.dart';
import 'package:flutter/material.dart';

class HouseList extends StatefulWidget {
  const HouseList({super.key});

  @override
  State<HouseList> createState() => _HouseListState();
}

class _HouseListState extends State<HouseList> {
  List houseList = [];

  // 获取房屋列表
  void getHouseList() async {
    try {
      final res = await http.get('/room');
      if (res['code'] != 10000) return ToastUtil.showError('获取数据失败');
      ToastUtil.showSuccess('获取数据成功');
      setState(() {
        houseList = res['data'];
      });
    } catch (e) {
      debugPrint('请求失败：$e');
      ToastUtil.showError('获取数据失败');
    }
  }

  @override
  void initState() {
    super.initState();
    getHouseList();
    eventBus.on<RefreshHouseList>().listen((event) {
      setState(() {
        houseList = [];
      });
      getHouseList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('房屋列表'),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body:
          houseList.isEmpty
              ? const Center(child: CircularProgressIndicator())
              : Container(
                padding: const EdgeInsets.all(10),
                child: Stack(
                  alignment: AlignmentDirectional.bottomCenter,
                  children: [
                    ListView.separated(
                      padding: const EdgeInsets.only(bottom: 80),
                      itemCount: houseList.length,
                      separatorBuilder: (BuildContext context, int index) {
                        return HouseItem(houseInfo: houseList[index]);
                      },
                      itemBuilder: (BuildContext context, int index) {
                        return Divider(
                          height: 10,
                          color: Color.fromARGB(255, 254, 247, 255),
                        );
                      },
                    ),
                    Container(
                      height: 80,
                      width: MediaQuery.of(context).size.width,
                      padding: EdgeInsets.all(10),
                      child: ElevatedButton(
                        onPressed: () {
                          Navigator.pushNamed(context, '/location');
                        },
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [Icon(Icons.add), Text('添加房屋')],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
    );
  }
}
